/*
 * @Author: liyin 2179253556@qq.com
 * @Date: 2023-04-28 16:42:59
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-07-22 11:32:11
 * @FilePath: util.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { ElLoading, transferProps } from 'element-plus'
import { AnyKindOfDictionary } from 'lodash'
export default {
  getYear() {
    const dt = new Date()
    const now = dt.getFullYear()
    return ('2009' + '-' + now)
  },
  // 获取当前可视高度
  getClientHeight() {
    const clientHeight = window.innerHeight
    return clientHeight
  },
  formatSize(size: any) {
    var size = size;
    if (!size)
      return "";
    var num = 1024.00
    if (size < num)
      return size + "B";
    if (size < Math.pow(num, 2))
      return (size / num).toFixed(2) + "KB"; //kb
    if (size < Math.pow(num, 3))
      return (size / Math.pow(num, 2)).toFixed(2) + "MB"; //M
    if (size < Math.pow(num, 4))
      return (size / Math.pow(num, 3)).toFixed(2) + "G"; //G
    return (size / Math.pow(num, 4)).toFixed(2) + "T"; //T
  },
  // 搜索框防抖函数
  debounce(cb: any, delay: any) {
    let timer: any = null
    return function (this: unknown, ...args: any) {
      if (timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(() => {
        cb.call(this, ...args)
      }, delay)
    }
  },
  /* 全局加载层设置 */
  baseLoading(index: any, text: any) {
    let loading
    if (!index) {
      console.log('进来了1')
      loading = ElLoading.service({
        lock: true,
        text: text,
        background: 'hsla(0,0%,100%,.8)',
      })
    } else {
      console.log('进来了2')
      loading = ElLoading.service({
        lock: true,
        text: text,
        spinner: 'vab-loading-type' + index,
        background: 'hsla(0,0%,100%,.8)',
      })
    }
    return loading
  },
  // 回显数据字典
  selectDictLabel(datas: any, value: any) {
    if (value === undefined) {
      return "";
    }
    var actions = [];
    Object.keys(datas).some((key) => {
      if (datas[key].dictValue == ('' + value)) {
        actions.push(datas[key].dictLabel);
        return true;
      }
    })
    if (actions.length === 0) {
      actions.push(value);
    }
    return actions.join('');
  },
  // 添加日期范围
  addDateRange(params: any, dateRange: any,) {
    let search = params;
    search.params = typeof (search.params) === 'object' && search.params !== null && !Array.isArray(search.params) ? search.params : {};
    dateRange = Array.isArray(dateRange) ? dateRange : [];
    search.params['beginTime'] = dateRange[0];
    search.params['endTime'] = dateRange[1];
    return search;
  },
  tansParams(params: any) {
    let result = ''
    for (const propName of Object.keys(params)) {
      const value = params[propName];
      var part = encodeURIComponent(propName) + "=";
      if (value !== null && value !== "" && typeof (value) !== "undefined") {
        if (typeof value === 'object') {
          for (const key of Object.keys(value)) {
            if (value[key] !== null && value[key] !== "" && typeof (value[key]) !== 'undefined') {
              let params = propName + '[' + key + ']';
              var subPart = encodeURIComponent(params) + "=";
              result += subPart + encodeURIComponent(value[key]) + "&";
            }
          }
        } else {
          result += part + encodeURIComponent(value) + "&";
        }
      }
    }
    return result
  },
  // 秒数转换成对应的时分秒
  getHMS(time: any) {
    let ms = time * 1000; // 转成毫秒
    let date = new Date(ms);
    let hour = date.getUTCHours();
    let minute = date.getMinutes();
    let second = date.getSeconds();
    let formatTime = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}:${second.toString().padStart(2, '0')}`;
    return formatTime
  },
  // 获取当前时间
  getInvalidTime() {
    let dt = new Date()
    const y = dt.getFullYear()
    const m = (dt.getMonth() + 1 + '').padStart(2, '0')
    const d = (dt.getDate() + '').padStart(2, '0')

    const hh = (dt.getHours() + '').padStart(2, '0')
    const mm = (dt.getMinutes() + '').padStart(2, '0')
    const ss = (dt.getSeconds() + '').padStart(2, '0')
    let now = `${y}年${m}月${d}日 ${hh}:${mm}:${ss}`
    return now
  },
  checkNumber(value: any, minLimit: any, maxLimit: any) {
    // 检查必须为整数
    value = Math.floor(value);
    if (value < minLimit) {
      value = minLimit;
    } else if (value > maxLimit) {
      value = maxLimit;
    }
    return value;
  },
  getNowTime(timestamp: any) {
    var date = new Date(timestamp * 1000)// 时间戳若为10位时需*1000
    var h = date.getHours() >= 10 ? date.getHours() : '0' + date.getHours()
    var m = date.getMinutes() >= 10 ? date.getMinutes() : '0' + date.getMinutes()
    var s = date.getSeconds() >= 10 ? date.getSeconds() : '0' + date.getSeconds()
    return `${h}:${m}:${s}`
  },
  getNowData(timestamp: any) {
    var date = new Date(timestamp * 1000)// 时间戳若为10位时需*1000
    var Y = date.getFullYear()
    var M = date.getMonth() + 1 >= 10 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1)
    var D = date.getDate() >= 10 ? date.getDate() : '0' + date.getDate()
    // 星期
    var week = date.getDay()
    return `${Y}-${M}-${D} ` + this.weeks(week)
  },
  // 把年月日转换成星期几
  weeks(s: any) {
    if (s === 0) {
      return '星期日'
    } else if (s === 1) {
      return '星期一'
    } else if (s === 2) {
      return '星期二'
    } else if (s === 3) {
      return '星期三'
    } else if (s === 4) {
      return '星期四'
    } else if (s === 5) {
      return '星期五'
    } else {
      return '星期六'
    }
  },
  fontSize(res: any) {
    var nowClientWidth = document.documentElement.clientWidth
    return res * (nowClientWidth / 1920)
  },
  // 用子级，查出父级
  // 查找所有父节点
  getAllParentArr(list: any, id: Number | string) {
    for (const i in list) {
      if (list[i].id === id) {
        // 查询到返回该数组对象
        // console.log(list[i])
        return [list[i]]
      }
      if (list[i].children) {
        const node: any = this.getAllParentArr(list[i].children, id)
        if (node !== undefined) {
          // 查询到把父节点连起来
          return node.concat(list[i])
        }
      }
    }
  },
  // 分配随机id，不重复
  generateUniqueId(list: any) {
    let id: any;
    do {
      id = Math.floor(100000 + Math.random() * 900000);
    } while (list.find((item: any) => item.id === id));
    return id;
  },
  // 两个数组比较
  updateData(allList: any, configList: any) {
    configList.forEach((item: any, index: number) => {
      const num = allList.findIndex((items: any) => Number(items.id) === Number(item.id))
      if (num !== -1) {
        // 如果找到了相同id的数据，则替换它
        configList.splice(index, 1, allList[num])
      } else {
        // 如果找不到就移除数据
        configList.splice(index, 1);
      }
    })
    return configList
  },
  // 如果你已经拿到了一个颜色值，并想生成一个具有相同颜色但带有透明度的新颜色，你可以使用CSS的RGBA或HSLA格式来定义颜色，并在其中指定透明度
  getNewColorWithTransparency(color: any, transparency: any, format: any) {
    const [r, g, b] = color.match(/\d+/g).map(Number);
    if (format === 'rgba') {
      return `rgba(${r}, ${g}, ${b}, ${transparency})`;
    } else if (format === 'hsla') {
      // 将RGB转换为HSL
      const hsl = this.rgbToHsl(r, g, b);
      return `hsla(${hsl[0]}, ${hsl[1]}%, ${hsl[2]}%, ${transparency})`;
    }
  },
  rgbToHsl(r: any, g: any, b: any) {
    (r /= 255), (g /= 255), (b /= 255);
    let max = Math.max(r, g, b),
      min = Math.min(r, g, b);
    let h: any, s: any, l = (max + min) / 2
    if (max === min) {
      h = s = 0; // achromatic
    } else {
      let d = max - min;
      s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
      switch (max) {
        case r:
          h = (g - b) / d + (g < b ? 6 : 0);
          break;
        case g:
          h = (b - r) / d + 2;
          break;
        case b:
          h = (r - g) / d + 4;
          break;
      }
      h /= 6;
    }

    return [Math.round(h * 360), Math.round(s * 100), Math.round(l * 100)];
  },
  isMobile() {
    if ((navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))) {
      return true // 手机端
    } else {
      return false // alert('PC端')
    }
  },
  // 将数组按n一组分割
  divideArrayIntoEqualParts(array: any, chunkSize: number) {
    console.log('jinliel')
    const length = array.length;
    const dividedArray = [];
    for (let i = 0; i < length; i += chunkSize) {
      const chunk = array.slice(i, i + chunkSize);
      dividedArray.push(chunk);
    }
    return dividedArray;
  }
}